package com.dkd.testClass.service.impl;

import com.dkd.common.core.redis.RedisCache;
import com.dkd.testClass.domain.TestClass;
import com.dkd.testClass.domain.TestStudent;
import com.dkd.testClass.mapper.TestClassMapper;
import com.dkd.testClass.service.ITestClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 班级表 服务实现类
 * </p>
 *
 * @author zwy
 * @since 2025-06-10
 */
@Service
public class TestClassServiceImpl implements ITestClassService {
    @Autowired
    private TestClassMapper testClassMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public List<TestClass> selectList(TestClass testClass) {
        return  testClassMapper.selectList(testClass);
    }

    @Override
    public TestClass selectById(Integer id) {
        TestClass testClass = testClassMapper.selectById(id);
        if (redisCache.hasKey("testClass"+id)){
            return redisCache.getCacheObject("testClass"+id);
        }
        redisCache.setCacheObject("testClass"+id,testClass,10, TimeUnit.MINUTES);
        return testClass;
    }

    @Override
    @Transactional
    public int insertTestClass(TestClass testClass) {
        testClassMapper.insertTestClass(testClass);
        return  insertTestStudent(testClass);
    }

    @Override
    public int deleteTestClass(Integer[] ids) {
        testClassMapper.deleteTestStudent(ids);
        return testClassMapper.deleteTestClass(ids);
    }

    @Override
    @Transactional
    public int updateTestClass(TestClass testClass) {
        testClassMapper.deleteTestStudent(new Integer[]{testClass.getId()});
        testClassMapper.updateTestClass(testClass);
        return insertTestStudent(testClass);
    }

    public int insertTestStudent(TestClass testClass) {
        List<TestStudent> studentList = testClass.getStudentList();
        studentList.forEach(testStudent -> {testStudent.setClassId(testClass.getId());});
        return testClassMapper.insertTestStudent(studentList);
    }

}
